package io.renren.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.Objects;

/**
 * @author: Mr.Wang
 * @description:
 * @create: $ $
 **/
public class QrCodeCreateUtil {

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static void genGR(String vip,String website, OutputStream output) throws WriterException, IOException {
        int width = 300;
        int height = 300;
        String format = "jpg";
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 纠错级别：L、M、Q、H
        hints.put(EncodeHintType.ERROR_CORRECTION, "H");
        BitMatrix bm = new MultiFormatWriter().encode(website, BarcodeFormat.QR_CODE, width, height, hints);
        //删除白边
        bm = deleteWhite(bm);
        BufferedImage image = toImage(bm);
        //添加logo
        //drawLogo(image,"1".equals(vip)?"http://nocimg.jinnoc.com/recog/20190509/e2f8585c76fc47de89b1f70df569dd88.png":null,width,height);
        //把二维码写到response的输出流
        ImageIO.write(image, format, output);
    }

    private static BufferedImage toImage(BitMatrix bm) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    /*private static void drawLogo(BufferedImage image,String logoFile, int width, int height) {
        try {
            int _width = image.getWidth();
            int _height = image.getHeight();
            if (StringUtils.isNotEmpty(logoFile)) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();

                // 读取Logo图片
                BufferedImage logo = ImageIO.read(getImageStream(logoFile));
                // 开始绘制logo图片
                //g.drawImage(logo, _width * 2 / 5, _height * 2 / 5, _width * 2 / 10, _height * 2 / 10, null);
                g.drawImage(logo.getScaledInstance(_width * 2 / 10,_height * 2 / 10,Image.SCALE_SMOOTH),_width * 2 / 5,_height * 2 / 5 ,null);
                g.dispose();
                logo.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/

    /**
     * 获取网络图片流
     * @param url
     * @return
     */
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }
}
